//
//  UIView+TYLoading.m
//  UnionMedApp
//
//  Created by 谢航宇_WORK on 2021/6/18.
//  Copyright © 2021 唐家钦. All rights reserved.
//

#import "UIView+TYLoading.h"
#import "Masonry.h"
#import "UIColor+TYColor.h"
@implementation UIView (TYLoading)

- (void)loadingWithStyle:(UIActivityIndicatorViewStyle)style {
     __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        UIView *bgView = [weakSelf viewWithTag:9009005];
        UIActivityIndicatorView * indicatorView = [weakSelf viewWithTag:9009006];
        if (!bgView) {
            bgView = [[UIView alloc]init];
            bgView.tag = 9009005;
            [weakSelf addSubview:bgView];
            [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.top.mas_equalTo(weakSelf);
            }];
            bgView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.5];
            indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:style];
            indicatorView.tag = 9009006;
            [bgView addSubview:indicatorView];
            [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.top.mas_equalTo(bgView);
            }];
        }
        
        [indicatorView startAnimating];
    });
     
      
}
- (void)loading {
    if (@available(iOS 13.0, *)) {
        [self loadingWithStyle:UIActivityIndicatorViewStyleMedium];
    }else {
        [self loadingWithStyle:UIActivityIndicatorViewStyleWhite];
    }
    
}
- (void)stopLoading {
     __weak typeof(self)weakSelf = self;
     dispatch_async(dispatch_get_main_queue(), ^{
          UIView *bgView = [weakSelf viewWithTag:9009005];
          UIActivityIndicatorView * indicatorView = [weakSelf viewWithTag:9009006];
          if (bgView || indicatorView) {
               [indicatorView stopAnimating];
               [bgView removeFromSuperview];
          }
     });
}
@end
